//
//  SGJLoginOnPasswordViewController.m
//  Sewage
//
//  Created by 宗庆猛 on 2017/5/30.
//  Copyright © 2017年 宗庆猛. All rights reserved.
//

#import "SGJLoginOnPasswordViewController.h"
#import "SGJLoginRegisterViewController.h"
#import "SGJSetupNewPasswordViewController.h"
#import "AFNetworkReachabilityManager.h"
#import "SGJNetworkTools.h"

#import "SGJTabController.h"
#import <YYModel.h>
#import "SGJUserModel.h"
@interface SGJLoginOnPasswordViewController ()
@property (weak, nonatomic) IBOutlet UIView *LoginAccount;
@property (weak, nonatomic) IBOutlet UIView *LoginPassword;
@property (weak, nonatomic) IBOutlet UITextField *LoginAccoutTextField;
@property (weak, nonatomic) IBOutlet UITextField *LoginPasswordTextField;
@property (weak, nonatomic) IBOutlet UIButton *LoginButton;

@end

@implementation SGJLoginOnPasswordViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // 注册通知监听TextField的编辑，编辑状态下整个View上移动
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    // 设置背景灰度
    self.view.backgroundColor = [UIColor colorWithWhite:.95 alpha:1];
    // 切圆角
    self.LoginAccount.layer.cornerRadius = 22;
    self.LoginPassword.layer.cornerRadius = 22;
    self.LoginButton.layer.cornerRadius = 22;
    
    // 取消输入框Textfield边线
    self.LoginAccoutTextField.borderStyle = UITextBorderStyleNone
    ;
    self.LoginPasswordTextField.borderStyle = UITextBorderStyleNone
    ;
    
}
// 点击隐藏密码按钮事件
- (IBAction)HidePasswordButton:(id)sender {
}

// 点击返回按钮响应事件
- (IBAction)ReturnLoginRegisterButton:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
// 点击忘记密码弹出控制器
- (IBAction)ForgetPasswordButton:(id)sender {
    SGJSetupNewPasswordViewController *setupNewPasswordVC = [[SGJSetupNewPasswordViewController alloc]init];
    [self.navigationController pushViewController:setupNewPasswordVC animated:YES];
}
// 点击登陆按钮响应事件
- (IBAction)LoginButton:(id)sender {
    
    [self MonitoringNetwork];
    //[String type:手动(不用传)/自动登录("zidong")]，[String tel:电话(账号)登录],[String pwd:登录密码]
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    //params[@"type"] = @"";
    //zidong  type
    params[@"tel"] = self.LoginAccoutTextField.text;
    params[@"pwd"] = self.LoginPasswordTextField.text;
    [[SGJNetworkTools sharedNetworkTool] loginWithUrlString:kGetUserLoginUrl parameters:params method:@"POST" callBack:^(id responseObject) {
        NSLog(@"登录%@",responseObject);
        
        if ([responseObject[@"retCode"] integerValue] == 0) {
            
            SGJUserModel *userModel = [SGJUserModel yy_modelWithJSON:responseObject[@"retData"]];
            [[NSUserDefaults standardUserDefaults] setObject:userModel.userId forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults] setObject:userModel.salt forKey:@"salt"];
            SGJTabController *tabVc = [[SGJTabController alloc] init];
            [self presentViewController:tabVc animated:YES completion:nil];
            //[self.navigationController pushViewController:tabVc animated:YES];
        }else{
            NSLog(@"登录请求有误");
        }
    }];
    
}
// 隐藏导航栏
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// 写一个方法取到编辑状态下的textfield
//- (void)getIsEditingView:(UIView *)rootView {
//    for (UIView *subView in rootView.subviews) {
//        if ([subView isKindOfClass:[UITextField class]]) {
//            if (((UITextField *)subView).isEditing) {
//                self.LoginAccoutTextField = subView;
//                return;
//            }else if (((UITextField *)subView).isEditing){
//                self.LoginAccoutTextField = subView;
//                return;
//            }
//        }
//        [self getIsEditingView:subView];
//    }
//}
// 计算已经拿到的textfield在屏幕中的位置
- (CGFloat)screenViewYValue:(UIView *)textfield {
    CGFloat y = 0;
    for (UIView *view = textfield; view; view = view.superview) {
        y += view.frame.origin.y;
        if ([view isKindOfClass:[UIScrollView class]]) {
            // 如果父视图是UIScrollView则要去掉内容滚动的距离
            UIScrollView* scrollView = (UIScrollView*)view;
            y -= scrollView.contentOffset.y;
        }
    }
    return y;
}

// 拿到的这个位置来进行视图上移处理, 也就是通知执行的方法
- (void)keyboardWillShow:(NSNotification *)noti {
    // 拿到正在编辑中的textfield
//    [self getIsEditingView:self.view];
    // textfield的位置
    CGFloat viewY = [self screenViewYValue:self.LoginAccoutTextField];
    // 键盘的Y值
    NSDictionary *userInfo = [noti userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyboardEndY = value.CGRectValue.origin.y;
    // 动画
    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    [UIView animateWithDuration:duration.doubleValue animations:^{
        if (viewY+30 > keyboardEndY) {
            CGRect rect = self.view.frame;
            rect.origin.y += keyboardEndY - (viewY+180);
            self.view.frame = rect;
        }
    }];
}

- (void)keyboardWillHide:(NSNotification *)noti {
    CGRect rect = self.view.frame;
    rect.origin.y = 0;
    self.view.frame = rect;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

// 视图销毁移除通知
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
// 监测网络判断手机号是否正确
- (void)MonitoringNetwork{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 此条件下没有网
        if (status == AFNetworkReachabilityStatusNotReachable) {
            //创建alert
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络不可用,请检查您的网络" preferredStyle:UIAlertControllerStyleAlert];
            //添加action
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action){
                NSLog(@"点击了取消");
            }];
            [alert addAction:action1];
            //显示alert
            [self presentViewController:alert animated:YES completion:nil];
        }
        // 如果有网判断手机号
        if (status != AFNetworkReachabilityStatusNotReachable) {
            
            BOOL answerKey = [self RegularlyDetermineTheMobilePhoneNumberFormat:self.LoginAccoutTextField.text];
            
            if (!answerKey) {
                //创建alert
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"手机号格式不正确" preferredStyle:UIAlertControllerStyleAlert];
                //添加action
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action){
                    NSLog(@"点击了取消");
                }];
                [alert addAction:action1];
                //显示alert
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                NSLog(@"手机号格式正确");
            }
            
        }
        
        // 当网络状态改变时调用
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"手机自带网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");
                break;
        }
    }];
    
    //开始监控
    [manager startMonitoring];
}

// 正则判断手机号
- (BOOL)RegularlyDetermineTheMobilePhoneNumberFormat:(NSString*)phone{
    phone = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (phone.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:phone];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:phone];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:phone];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

// 网络请求数据，拿到登陆返回值





/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
